package com.mc.web;

import org.apache.log4j.Logger;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.mc.model.Menu;
import com.mc.model.Path;
import com.mc.model.User;
import com.mc.service.MenuService;
import com.mc.service.UserService;
import com.mc.utils.PathUtil;
@Controller
@SessionAttributes("user")
public class LoginAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LoginAction.class);

	@Autowired
	private UserService userService;
	
	@Autowired private MenuService menuService;
	
	private Path path = null;
	
	private String uri = "";
	/**
	 * 
	 * @param modelMap
	 * @param request
	 * @return  后台登陆界面
	 */
	@RequestMapping("loginui")
    public String loginui(ModelMap modelMap,HttpServletRequest request)
    {
		/*path = new Path();
		path.setPackageName("login");
		path.setViewName("login");
		path.setViewTitle("登录");*/
		uri = (String) request.getAttribute("uri");
		logger.info(uri);
		path = PathUtil.setPathParams(new String[]{"PackageName:login","ViewName:login","ViewTitle:登录","smenu:login"});		
        
		return PathUtil.returnStr(path,modelMap);	
    }
	/**
	 * 
	 * @param username  用户名
	 * @param password 密码
	 * @param modelMap 
	 * @param session
	 * @param request
	 * @return 验证登陆，成功则进入后台管理界面
	 */
	@RequestMapping("/login")
	public String login(@RequestParam(value="username",required=true) String username,
			@RequestParam(value="password",required=true) String password,ModelMap modelMap,
			HttpSession session,HttpServletRequest request)
    {
		User user = userService.selectByUserName(username);
		//logger.info(user.toString());
		if(user!=null)
		{
			if(user.getPwd().equals(password))
			{
				//logger.info("success");
				path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:InsertAcaIntro","ViewTitle:添加学院简介"});				
				List<Menu> menus = menuService.selectAllMenu();
				modelMap.addAttribute("pmenus", menus);
				modelMap.addAttribute("user", user);
				if(uri!=null && !uri.equals(""))
				{
					String path = request.getContextPath();
					uri = uri.replace(path, "");
					return "redirect:" + uri;
				
				}//logger.info(session.getAttribute("user").toString());
				return "forward:/backend/newsmagui";
			}
		}
		modelMap.addAttribute("missPass", true);
    	return "forward:/loginui";
    }
}
